import window from '@ohos.window';
import display from '@ohos.display';
import { GlobalContext } from '../common/utils/GlobalContext';
import { CommonConstant } from '../common/constant/CommonConstant';

export default class FontSizeWindowModel {
  private windowStage?: window.WindowStage;
  private subWindowClass?: window.Window;

  static getInstance(): FontSizeWindowModel {
    let instance: FontSizeWindowModel = GlobalContext.getContext().getObject('windowModel') as FontSizeWindowModel;
    if (instance === undefined) {
      instance = new FontSizeWindowModel();
      GlobalContext.getContext().setObject('windowModel', instance)
    }
    return instance;
  }


  setWindowStage(ws: window.WindowStage) {
    this.windowStage = ws
  }

  createSubWindow() {
    if (this.windowStage === undefined) {
      return
    }

    //创建子窗口
    this.windowStage.createSubWindow(CommonConstant.APP_FONT_SIZE_SUB_WINDOW, (err, data: window.Window) => {
      if (err.code) {
        console.error(`打印 ------  err: ${err.name} code: ${err.code}  message: ${err.message} `)
        return
      }

      this.subWindowClass = data
      let screenW = display.getDefaultDisplaySync().width
      let screenH = display.getDefaultDisplaySync().height

      let windowW = screenW * CommonConstant.SUB_WINDOW_WIDTH_RATIO
      let windowH = windowW / CommonConstant.SUB_WINDOW_ASPECT_RATIO

      let moveX = (screenW - windowW) / 2
      let moveY = (screenH - windowH) / 2
      console.error(`打印 ------  window 信息 screenW : ${screenW} screenH: ${screenH}
       windowW: ${windowW} windowH: ${windowH} moveX: ${moveX} moveY: ${moveY} `)

      this.subWindowClass.moveWindowTo(moveX, moveY).then(() => {
        console.error(`打印 ------  moveWindowTo 成功`)
      }).catch((err) => {
        console.error(`打印 ------  moveWindowTo 失败: ${err.name} code: ${err.stack}  message: ${err.message} `)
      })

      this.subWindowClass.resize(windowW, windowH).then(() => {
        console.error(`打印 ------  resize 成功:`)
      }).catch((err) => {
        console.error(`打印 ------  resize 失败: ${err.name} code: ${err.stack}  message: ${err.message} `)
      })
      this.subWindowClass.setUIContent("pages/subwindow/FontSettingPage").then(() => {
        console.error(`打印 ------  setUIContent 成功: `)
      }).catch((err) => {
        console.error(`打印 ------  setUIContent 失败: ${err.name} code: ${err.stack}  message: ${err.message} `)
      })

      this.subWindowClass.showWindow().then(() => {
        console.error(`打印 ------  showWindow 成功`)
      }).catch((err) => {
        console.error(`打印 ------  showWindow 失败: ${err.name} code: ${err.stack}  message: ${err.message} `)
      })
    })
  }

  destroySubWindow() {
    this.subWindowClass.destroyWindow((err) => {
      //fail
    })
  }
}